# src/main.py
import sys
import os
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from backend.api.routers import load_data, user, prediction_analysis, auth, real_time_prediction, multi_prediction, data_sync, yesterday_data, dataset_overview, model_evaluation, enhanced_training  # 导入所有路由
from backend.config.database import Base, engine
from backend.config.settings import settings
from backend.utils.exceptions import (
    global_exception_handler, 
    validation_exception_handler,
    BaseAPIException
)

# 导入所有实体类以确保表被创建
from backend.entities.load_data_new import LoadData
from backend.entities.weather_daily import WeatherDaily  
from backend.entities.weather_data_new import WeatherData
from backend.entities.user import User
from backend.entities.user_info import UserInfo
from backend.entities.holiday import HolidayInfo, HolidayRules
from backend.entities.prediction import PredResult, ModelEval
from backend.entities.feat_imp import FeatImp
from backend.entities.model_eval import ModelEval as ModelEvaluation
from backend.entities.model_training_log import ModelTrainingLog
from backend.entities.shap_analysis import ShapAnalysis

# 初始化数据库表
Base.metadata.create_all(bind=engine)

app = FastAPI(
    title="LFforecast API",
    description="电力负载预测系统",
    version="1.0.0",
    openapi_url=f"{settings.API_PREFIX}/openapi.json"
)

# CORS配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 开发环境允许所有源
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(
    auth.router,
    prefix=settings.API_PREFIX,
    tags=["Authentication"]
)
app.include_router(
    load_data.router,
    prefix=settings.API_PREFIX,
    tags=["Load Data"]
)
app.include_router(
    user.router,
    prefix=settings.API_PREFIX,
    tags=["Users"]
)
app.include_router(
    prediction_analysis.router,
    prefix=settings.API_PREFIX,
    tags=["Prediction Analysis"]
)
# # 注册新的模型训练和实时预测路由
# app.include_router(
#     model_training.router,
#     prefix=settings.API_PREFIX,
#     tags=["Model Training"]
# )
app.include_router(
    real_time_prediction.router,
    prefix=settings.API_PREFIX,
    tags=["Real-time Prediction"]
)
app.include_router(
    multi_prediction.router,
    prefix=settings.API_PREFIX,
    tags=["Multi Prediction"]
)
app.include_router(
    data_sync.router,
    prefix=settings.API_PREFIX,
    tags=["Data Sync"]
)
app.include_router(
    yesterday_data.router,
    prefix=settings.API_PREFIX,
    tags=["Yesterday Data"]
)
app.include_router(
    dataset_overview.router,
    prefix=settings.API_PREFIX,
    tags=["Dataset Overview"]
)
app.include_router(
    model_evaluation.router,
    prefix=settings.API_PREFIX,
    tags=["Model Evaluation"]
)
app.include_router(
    enhanced_training.router,
    prefix=f"{settings.API_PREFIX}/enhanced-training",
    tags=["Enhanced Training"]
)

# 注册全局异常处理器
app.add_exception_handler(BaseAPIException, global_exception_handler)
app.add_exception_handler(RequestValidationError, validation_exception_handler)
app.add_exception_handler(Exception, global_exception_handler)

@app.middleware("http")
async def log_requests(request, call_next):
    """请求日志中间件"""
    import time
    import logging
    
    logger = logging.getLogger(__name__)
    start_time = time.time()
    
    # 记录请求
    logger.info(f"Request: {request.method} {request.url}")
    
    response = await call_next(request)
    
    # 记录响应
    process_time = time.time() - start_time
    logger.info(f"Response: {response.status_code} - {process_time:.3f}s")
    
    return response

# 如果直接运行此文件，请使用项目根目录的 run_server.py
if __name__ == "__main__":
    print("⚠️  请使用项目根目录的 run_server.py 来启动服务器")
    print("   python run_server.py")
    import sys
    sys.exit(1)
